<template>
  <div class="tenant-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>租户管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增租户
          </el-button>
        </div>
      </template>

      <!-- 批量操作工具栏 -->
      <div class="batch-toolbar">
        <el-button type="warning" @click="handleBatchExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-upload
          class="upload-demo"
          action="/api/system/tenant/import"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          :show-file-list="false"
          accept=".xlsx,.xls"
        >
          <el-button type="success">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
        </el-upload>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedTenants.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="租户名称">
          <el-input v-model="searchForm.tenantName" placeholder="请输入租户名称" clearable />
        </el-form-item>
        <el-form-item label="租户编码">
          <el-input v-model="searchForm.tenantCode" placeholder="请输入租户编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期时间">
          <el-date-picker
            v-model="expireTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 租户列表表格 -->
      <el-table 
        :data="tenantList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="tenantName" label="租户名称" min-width="150" />
        <el-table-column prop="tenantCode" label="租户编码" width="120" />
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="contactEmail" label="联系邮箱" min-width="150" show-overflow-tooltip />
        <el-table-column prop="expireTime" label="到期时间" width="120">
          <template #default="{ row }">
            <div class="expire-cell">
              <span :class="{ 'text-danger': isExpired(row.expireTime) }">
                {{ formatDate(row.expireTime) }}
              </span>
              <el-tag v-if="isNearExpiry(row.expireTime)" type="warning" size="small">
                即将到期
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="maxUsers" label="最大用户数" width="100" />
        <el-table-column prop="maxStorage" label="存储空间(GB)" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="row.status === 0 ? 'danger' : 'success'" 
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="primary" link @click="handleConfig(row)">配置</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑租户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="tenantFormRef"
        :model="tenantForm"
        :rules="tenantRules"
        label-width="100px"
      >
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="tenantForm.tenantName" placeholder="请输入租户名称" maxlength="50" show-word-limit :disabled="!!tenantForm.id" />
        </el-form-item>
        <el-form-item label="租户编码" prop="tenantCode">
          <el-input v-model="tenantForm.tenantCode" placeholder="请输入租户编码" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="tenantForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="tenantForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="tenantForm.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker
            v-model="tenantForm.expireTime"
            type="date"
            placeholder="选择到期时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="最大用户数" prop="maxUsers">
          <el-input-number v-model="tenantForm.maxUsers" :min="1" :max="10000" />
        </el-form-item>
        <el-form-item label="存储空间(GB)" prop="maxStorage">
          <el-input-number v-model="tenantForm.maxStorage" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="tenantForm.status"
            :active-value="0"
            :inactive-value="1"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <span class="status-tips" :class="tenantForm.status === 0 ? 'status-enable' : 'status-disable'">
            {{ tenantForm.status === 0 ? '租户可正常使用' : '租户已被禁用' }}
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="tenantForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 租户配置对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      title="租户配置"
      width="500px"
      @close="handleConfigDialogClose"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="120px"
      >
        <el-form-item label="API调用次数" prop="maxApiCalls">
          <el-input-number v-model="configForm.maxApiCalls" :min="100" :max="1000000" />
        </el-form-item>
        <el-form-item label="数据处理量" prop="maxDataProcessing">
          <el-input-number v-model="configForm.maxDataProcessing" :min="1" :max="10000" />
          <span class="unit">GB</span>
        </el-form-item>
        <el-form-item label="并发用户数" prop="maxConcurrentUsers">
          <el-input-number v-model="configForm.maxConcurrentUsers" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="数据保留天数" prop="dataRetentionDays">
          <el-input-number v-model="configForm.dataRetentionDays" :min="7" :max="365" />
        </el-form-item>
        <el-form-item label="高级功能" prop="features">
          <el-checkbox-group v-model="configForm.features">
            <el-checkbox label="dataAnalysis">数据分析</el-checkbox>
            <el-checkbox label="reportExport">报表导出</el-checkbox>
            <el-checkbox label="apiAccess">API访问</el-checkbox>
            <el-checkbox label="customDashboard">自定义仪表板</el-checkbox>
          </el-checkbox-group>
          <div class="feature-tips">
            <el-icon><InfoFilled /></el-icon>
            <span>选择租户可使用的功能模块</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="configSubmitLoading" @click="handleConfigSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Download, Upload, Delete, InfoFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import {
  getTenantPage,
  createTenant,
  updateTenant,
  deleteTenant,
  updateTenantStatus,
  updateTenantConfig
} from '@/api/system'
import type { Tenant, TenantConfig } from '@/types/api'

const loading = ref(false)
const tenantList = ref<Tenant[]>([])
const selectedTenants = ref<Tenant[]>([])
const expireTimeRange = ref<string[]>([])

const searchForm = reactive({
  tenantName: '',
  tenantCode: '',
  status: undefined as number | undefined,
  expireStartTime: '',
  expireEndTime: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const dialogVisible = ref(false)
const submitLoading = ref(false)
const tenantFormRef = ref<FormInstance>()

const tenantForm = reactive({
  id: undefined as number | undefined,
  tenantName: '',
  tenantCode: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  expireTime: '',
  maxUsers: 100,
  maxStorage: 10,
  status: 0,
  remark: ''
})

const tenantRules: FormRules = {
  tenantName: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
  tenantCode: [{ required: true, message: '请输入租户编码', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  expireTime: [{ required: true, message: '请选择到期时间', trigger: 'change' }],
  maxUsers: [{ required: true, message: '请输入最大用户数', trigger: 'blur' }],
  maxStorage: [{ required: true, message: '请输入存储空间', trigger: 'blur' }]
}

const configDialogVisible = ref(false)
const configSubmitLoading = ref(false)
const configFormRef = ref<FormInstance>()
const currentTenantId = ref<number>()

const configForm = reactive<TenantConfig>({
  maxApiCalls: 10000,
  maxDataProcessing: 100,
  maxConcurrentUsers: 50,
  dataRetentionDays: 30,
  features: []
})

const configRules: FormRules = {
  maxApiCalls: [{ required: true, message: '请输入API调用次数', trigger: 'blur' }],
  maxDataProcessing: [{ required: true, message: '请输入数据处理量', trigger: 'blur' }],
  maxConcurrentUsers: [{ required: true, message: '请输入并发用户数', trigger: 'blur' }],
  dataRetentionDays: [{ required: true, message: '请输入数据保留天数', trigger: 'blur' }]
}

const dialogTitle = computed(() => 
  tenantForm.id ? '编辑租户' : '新增租户'
)

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const isExpired = (expireTime: string) => {
  if (!expireTime) return false
  return new Date(expireTime) < new Date()
}

const isNearExpiry = (expireTime: string) => {
  if (!expireTime) return false
  const expiryDate = new Date(expireTime)
  const today = new Date()
  const diffDays = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays <= 30 && diffDays > 0
}

const fetchTenantList = async () => {
  loading.value = true
  try {
    // 处理到期时间范围
    if (expireTimeRange.value && expireTimeRange.value.length === 2) {
      searchForm.expireStartTime = expireTimeRange.value[0]
      searchForm.expireEndTime = expireTimeRange.value[1]
    } else {
      searchForm.expireStartTime = ''
      searchForm.expireEndTime = ''
    }
    
    // 移除空值参数
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await getTenantPage(params)
    tenantList.value = response.records
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取租户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchTenantList()
}

const handleReset = () => {
  searchForm.tenantName = ''
  searchForm.tenantCode = ''
  searchForm.status = undefined
  searchForm.expireStartTime = ''
  searchForm.expireEndTime = ''
  expireTimeRange.value = []
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchTenantList()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchTenantList()
}

const handleAdd = () => {
  tenantForm.id = undefined
  tenantForm.tenantName = ''
  tenantForm.tenantCode = ''
  tenantForm.contactName = ''
  tenantForm.contactPhone = ''
  tenantForm.contactEmail = ''
  tenantForm.expireTime = ''
  tenantForm.maxUsers = 100
  tenantForm.maxStorage = 1000
  tenantForm.status = 0
  tenantForm.remark = ''
  dialogVisible.value = true
}

const handleEdit = (row: Tenant) => {
  tenantForm.id = row.id
  tenantForm.tenantName = row.tenantName
  tenantForm.tenantCode = row.tenantCode
  tenantForm.contactName = row.contactName
  tenantForm.contactPhone = row.contactPhone
  tenantForm.contactEmail = row.contactEmail
  tenantForm.expireTime = row.expireTime
  tenantForm.maxUsers = row.maxUsers
  tenantForm.maxStorage = row.maxStorage
  tenantForm.status = row.status
  tenantForm.remark = row.remark || ''
  dialogVisible.value = true
}

const handleToggleStatus = async (row: Tenant) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 0 ? '禁用' : '启用'}租户"${row.tenantName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateTenantStatus(row.id, row.status === 0 ? 1 : 0)
    ElMessage.success(`${row.status === 0 ? '禁用' : '启用'}成功`)
    fetchTenantList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleConfig = async (row: Tenant) => {
  currentTenantId.value = row.id
  configForm.maxApiCalls = row.config?.maxApiCalls || 10000
  configForm.maxDataProcessing = row.config?.maxDataProcessing || 100
  configForm.maxConcurrentUsers = row.config?.maxConcurrentUsers || 50
  configForm.dataRetentionDays = row.config?.dataRetentionDays || 30
  configForm.features = row.config?.features || []
  configDialogVisible.value = true
}

const handleDelete = async (row: Tenant) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除租户"${row.tenantName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteTenant(row.id)
    ElMessage.success('删除成功')
    fetchTenantList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSelectionChange = (selection: Tenant[]) => {
  selectedTenants.value = selection
}

const handleBatchDelete = async () => {
  if (selectedTenants.value.length === 0) {
    ElMessage.warning('请选择要删除的租户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedTenants.value.length}个租户吗？`,
      '提示',
      { type: 'warning' }
    )
    
    const deletePromises = selectedTenants.value.map(tenant => deleteTenant(tenant.id))
    await Promise.all(deletePromises)
    ElMessage.success('批量删除成功')
    selectedTenants.value = []
    fetchTenantList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const handleBatchExport = () => {
  const exportData = tenantList.value.map(tenant => ({
    '租户名称': tenant.tenantName,
    '租户编码': tenant.tenantCode,
    '联系人': tenant.contactName,
    '联系电话': tenant.contactPhone,
    '联系邮箱': tenant.contactEmail,
    '到期时间': formatDate(tenant.expireTime),
    '最大用户数': tenant.maxUsers,
    '存储空间(GB)': tenant.maxStorage,
    '状态': tenant.status === 0 ? '启用' : '禁用',
    '创建时间': formatDateTime(tenant.createTime)
  }))
  
  const ws = XLSX.utils.json_to_sheet(exportData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '租户列表')
  XLSX.writeFile(wb, `租户列表_${new Date().toLocaleDateString('zh-CN')}.xlsx`)
}

const handleImportSuccess = (response: any) => {
  if (response.success) {
    ElMessage.success('导入成功')
    fetchTenantList()
  } else {
    ElMessage.error(response.message || '导入失败')
  }
}

const handleImportError = () => {
  ElMessage.error('导入失败')
}

const handleSubmit = async () => {
  if (!tenantFormRef.value) return
  
  try {
    await tenantFormRef.value.validate()
    submitLoading.value = true
    
    if (tenantForm.id) {
      await updateTenant(tenantForm.id, tenantForm)
      ElMessage.success('更新成功')
    } else {
      await createTenant(tenantForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchTenantList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleConfigSubmit = async () => {
  if (!configFormRef.value || !currentTenantId.value) return
  
  try {
    await configFormRef.value.validate()
    configSubmitLoading.value = true
    
    await updateTenantConfig(currentTenantId.value, configForm)
    ElMessage.success('配置更新成功')
    configDialogVisible.value = false
    fetchTenantList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('配置更新失败')
    }
  } finally {
    configSubmitLoading.value = false
  }
}

const handleDialogClose = () => {
  tenantFormRef.value?.resetFields()
}

const handleConfigDialogClose = () => {
  configFormRef.value?.resetFields()
  currentTenantId.value = undefined
}

onMounted(() => {
  fetchTenantList()
})
</script>

<style scoped>
.tenant-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-toolbar {
  margin-bottom: 15px;
  padding: 10px 15px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.batch-toolbar span {
  margin-right: auto;
  font-weight: 500;
  color: #1890ff;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.text-danger {
  color: #f56c6c;
}

.unit {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.expire-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.expire-cell .el-tag {
  font-size: 10px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
}

.upload-demo {
  display: inline-block;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.status-tips {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.status-enable {
  color: #67c23a;
}

.status-disable {
  color: #f56c6c;
}

.feature-tips {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

@media (max-width: 768px) {
  .batch-toolbar {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .batch-toolbar span {
    width: 100%;
    margin-bottom: 8px;
  }
  
  .search-form {
    padding: 15px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
}
</style>